package com.eliauk.democommon.controler;


import com.eliauk.democommon.common.Result;
import com.eliauk.democommon.service.OssService;
import com.eliauk.democommon.utils.file.MyFileUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.Set;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${file.allow-type}")
    private Set<String> allowTypeSet;

    @Value("${spring.servlet.multipart.max-file-size}")
    private long maxSize;

    @Autowired
    private OssService ossService;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public Result<?> upload(@RequestPart("file") MultipartFile file) throws IOException {
        if (MyFileUtil.checkSize(file,maxSize))
        {
            Result.error("文件大小不符合");
        }
        if (MyFileUtil.checkFormat(file,allowTypeSet)){
            Result.error("文件类型不符合");
        }
        String url = ossService.upload(file.getBytes(), file.getOriginalFilename());
        return Result.ok(url);
    }
}
